﻿using System;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Web;
namespace SystemX.WebControls
{
    /// <summary>
    /// wrapper control for js
    /// </summary>
    public class SiteJScript:WebControl
    {
        private string scriptRelativeToRoot = string.Empty;
		public static string ScriptTemplate = "{0}<script type='text/javascript' src='{1}{2}'></script>";
        public string ScriptRelativeToRoot
        {
            get { return scriptRelativeToRoot; }
            set { scriptRelativeToRoot = value; }
        }
        /// <summary>
        /// 是否末尾加换行符
        /// </summary>
        public bool Linebreak { get; set; }
		public bool Encoded { get; set; }
		public bool DebugOnly { get; set; }
		public bool ReleasedOnly { get; set; }

        public string Script
        {
            get {
				var str = String.Format(ScriptTemplate, (Linebreak ? System.Environment.NewLine : ""), SystemX.Web.Utils.AbsoluteWebRoot, ScriptRelativeToRoot);
				if(scriptRelativeToRoot.StartsWith("http",StringComparison.InvariantCultureIgnoreCase)){
					str = string.Format(ScriptTemplate, (Linebreak ? System.Environment.NewLine : ""), "", ScriptRelativeToRoot);	
				}
                
				if (Encoded) {
					str = HttpUtility.HtmlEncode(str);
				};
#if !DEBUG
				if (DebugOnly) { 
					str="";
				}
#else
				if (ReleasedOnly) {
					str = "";
				}
#endif
				return str;
				
			}
        }

        protected override void Render(HtmlTextWriter writer)
        {
            if (this.Site != null && this.Site.DesignMode)
            {
                // TODO: show a bmp or some other design time thing?
                //writer.Write("[" + this.ID + "]");
            }
            else
            {
				if (!string.IsNullOrEmpty(this.Script))
				{
					writer.Write(this.Script);
				}
            }
        }
    }
}
